#region using
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
#endregion

public partial class MailSend : System.Web.UI.Page
{
	#region [ ImageID ]
	/// <summary>
	/// Gets or sets the CAPTCHA image ID
	/// </summary>
	/// <value>ID</value>
	private string ImageID
	{
		get
		{
			object obj_id = this.ViewState["IMAGE_ID"];
			if (obj_id == null) return "";
			return obj_id.ToString();
		}
		set
		{
			if (value != null)
			{
				this.ViewState["IMAGE_ID"] = value;
			}
		}
	}
	#endregion

	#region [ Vars ]
	// variable that contain an error message
	public string reportMSG = "";
	#endregion

	#region [ ReadAndTestUploadFile ]
	/// <summary>
	/// Recives the FileUpload control and and tets the uploaded file.
	/// </summary>
	/// <param name="input">name of FileUpload control.</param>
	/// <param name="bitFile">byte array that contains the uploaded file</param>
	/// <param name="error">error message with the code of it.</param>
	/// <returns>retrn TRUE if file exists and the size of it isn't bigger then the value of specified field in WebConfig("maxFileSize")</returns>
	private static bool ReadAndTestUploadFile(System.Web.UI.WebControls.FileUpload input, out byte[] bitFile, out string error)
	{
		//default value of error message
		error = "00 no errors";
		bitFile = null;
		// checking of file for existence
		if (input.PostedFile == null || input.PostedFile.ContentLength < 3)
		{
			error = "17 Uploadig file Error";
			return false;
		}
		// checking the size of file
		if (input.PostedFile.ContentLength > Convert.ToInt32(ConfigurationManager.AppSettings["MaxFileSize"]))
		{
			error = "07 too big file size";
			return false;
		}
		// loading file from FileUpload control to the byte array
		try
		{
			Stream stream = input.PostedFile.InputStream;
			int length = input.PostedFile.ContentLength;
			byte[] FileBites = new byte[length];
			stream.Read(FileBites, 0, length);

			if (FileBites != null && FileBites.Length > 0)
				bitFile = FileBites;
		}
		catch (Exception)
		{
			// error message for any general exeption
			error = "18 general error while uploading";
			return false;
		}
		return true;
	}
	#endregion

	#region [ Ckecking users data Local]
	/// <summary>
	/// Verification of data entered by user.
	/// </summary>
	/// <param name="securityToken">string that contains crypted answer for the CAPTCHA WebService(not to be changed by user)</param>
	/// <returns>string array with error messages</returns>
	private string[] DataCkecking(string securityToken)
	{
		string[] report = new string[5];
		if (string.IsNullOrEmpty(tbName.Text))
			report[0] = "03 no name entered";
		if (string.IsNullOrEmpty(tbEmail.Text))
			report[1] = "01 incorect E-mail of sender";
		if (string.IsNullOrEmpty(tbSubject.Text))
			report[2] = "06 no subject entered";
		if (string.IsNullOrEmpty(CaptchaAnswer.Text))
			report[3] = "22 CAPTCH answer text is empty";
		if (string.IsNullOrEmpty(securityToken))
		    report[4] = "23 securityToken is empty";
		return report;

	}
	#endregion

	#region [ GetImage ]
	/// <summary>
	/// Gets the image ID.
	/// </summary>
	/// <returns></returns>
	protected string GetImageID()
	{
		return ImageID;
	}
	#endregion

	#region [ Page_Load ]
	/// <summary>
	/// Handles the Load event of the Page control.
	/// </summary>
	/// <param name="sender">The source of the event.</param>
	/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
	protected void Page_Load(object sender, EventArgs e)
	{
		// ckecks the existing of a CAPTCHA image id or generates a new one if it's empty 
		if (string.IsNullOrEmpty(ImageID))
		{
			ImageID = Guid.NewGuid().ToString();
			this.ViewState.Add("IMAGE_ID", ImageID);
		}
		// trying to connect to the Web Site the FCKeditor control
		try
		{
			int index = Request.Url.AbsoluteUri.LastIndexOf("/");
			this.bodyEditor.BasePath = Request.Url.AbsoluteUri.Remove(index) + "/FCKeditor/";
		}
		catch (Exception)
		{
			// error message in case of FCKeditor not connected
			reportMSG = "19 FCKeditor notFound";
		}
	}
	#endregion

	#region [ GetErrorText ]
	/// <summary>
	/// Gets full text of any error or other WebService message from ErrorList.xml
	/// </summary>
	/// <param name="reportMSG">Short text of error or other message with code of it</param>
	/// <returns></returns>
		private static string GetErrorText(string reportMSG)
		{
			// extracts error code from  a short message, on the base of it code recive full error message from Menager class 
			string errorText = Menager.GetErrorText(reportMSG.Substring(0, 2));
			//if(reportMSG.Substring(0,2) != "00")
			if (string.IsNullOrEmpty(errorText))
				return reportMSG;
			else
				return errorText;
		}
	#endregion

	#region [ Button1_Click ]
	/// <summary>
	/// Handles the Click event of the Button1 control.
	/// </summary>
	/// <param name="sender">The source of the event.</param>
	/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
	protected void Button1_Click(object sender, EventArgs e)
	{
		// this region contain all local data that will be used for checking and sending mail
		#region [ Local Vars ]

		// default error message
		string reportMSG = "";
		// your personal name that will be used to send you an Email(stored in WebConfig file)
		string toName = ConfigurationManager.AppSettings["reciverName"];
		string subject = tbSubject.Text;
		string body = bodyEditor.Value;
		// Email of the sender
		string senderEmail = tbEmail.Text;
		// name of the sender
		string fromName = tbName.Text;
		// your personal Email address that will be used to send you an Email(stored in WebConfig file)
		string reciverEmail = ConfigurationManager.AppSettings["reciverEmail"];
		// path of the file that contain publick Key for encrypting Email addresses(stored in WebConfig file)
		string filePath = this.Server.MapPath("~/App_Data/" + ConfigurationManager.AppSettings["publicKeyFileName"]);
		// your answer for the CAPTCHA picture
		string captchaValue = CaptchaAnswer.Text;
		string securityToken="";
		if (this.Cache[ImageID] != null)
		{
			securityToken = (string)this.Cache[ImageID];
		}
		else
		{
			reportMSG = "Cashed securityToken is null";
			//throw new NullReferenceException(reportMSG);
		}
		if (string.IsNullOrEmpty(securityToken))
		{
			reportMSG = "23 no security Token recived";
			ErrorOutput.Text = GetErrorText(reportMSG);
			return;
		}
		byte[] fileByte;
		byte[] AttFile = null;
		string AttacmentFileName = "";
		// parameter that shows if text of the body of the message will have HTML formating
		bool isBodyHTML = true;
		byte[] to;
		byte[] from;
		string localError = "";
		// reciving string array with possible errors
		string[] reportArray = DataCkecking(securityToken);

		#endregion

		// first of all we check the data you've entered in the DataCkecking method
		for (int i = 0; i < 5; i++)
		{
			if (!string.IsNullOrEmpty(reportArray[i]))
				// generaiting string with errors which includes <br /> tages
				localError += "<br /> " + Menager.GetErrorText(reportArray[i].Substring(0, 2));
		}
		// if string with previous errors isn't empty - error list is shown
		if (!string.IsNullOrEmpty(localError))
		{
			ErrorOutput.Text = localError;
		}
		// if no errors ocured - we are calling WebService which will send your an Email and return to you report message
		else
		{
			MyRealNet.MailerService.MailerService service = new MyRealNet.MailerService.MailerService();

			#region [ send Crypted E-mail ]
			// encrypting your and sender Email addresses 
			if (AsymetricEncryptor.EncryptData(reciverEmail, filePath, out to, out reportMSG))
				if (AsymetricEncryptor.EncryptData(senderEmail, filePath, out from, out reportMSG))
				{
					// checking attacment file to send Email with it
					if (InputFile.HasFile)
					{
						AttacmentFileName = InputFile.FileName;
						if (ReadAndTestUploadFile(InputFile, out fileByte, out reportMSG))
						{
							AttFile = fileByte;
							try
							{
								//sending Email
								if (service.MailSend(from, fromName, to, toName, subject, body, isBodyHTML, AttFile, AttacmentFileName, captchaValue, securityToken, out reportMSG))
									reportMSG = "20 mail is delivered successfully";
							}
							catch (Exception)
							{
								// catching any general exeption
								reportMSG = "21 sending error";
							}
						}
					}
					// if FileUpload control doesn't contain any file - we send Email without attacment
					else
					{
						try
						{
							if (service.MailSend(from, fromName, to, toName, subject, body, isBodyHTML, AttFile, AttacmentFileName, captchaValue, securityToken, out reportMSG))
								reportMSG = "20 mail is delivered successfully";
						}
						catch (Exception)
						{
							// catching any general exeption
							reportMSG = "21 sending error";
						}
					}
				}
			#endregion

			ErrorOutput.Text = GetErrorText(reportMSG);
		}
	}
	#endregion

}